package com.hcc.flow.server.controller.sys;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hcc.flow.server.annotation.LogAnnotation;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.dao.sys.AreaDao;
import com.hcc.flow.server.model.sys.Area;
import com.hcc.flow.server.service.sys.AreaService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 区域相关接口
 * 
 * @author 韩长志 2019-11-19
 *
 */
@Api(tags = "区域")
@RestController
@RequestMapping("/areas")
public class AreaController {

	@Autowired
	private AreaDao areaDao;
	@Autowired
	private AreaService areaService;

	@GetMapping("/all")
	@ApiOperation(value = "区域-所有区域")
	public JSONArray areasAll() {
		List<Area> areasAll = areaDao.listAll();
		JSONArray array = new JSONArray();
		setAreasTree(0L, areasAll, array);

		return array;
	}

	@GetMapping("/parents")
	@ApiOperation(value = "区域-顶级区域")
	public List<Area> listParents() {
		List<Area> parents = areaDao.listParents();
		return parents;
	}

	@GetMapping("/listByParentId/{id}")
	@ApiOperation(value = "区域-根据区域id查询子区域")
	public ApiResult<?> listByParentId(@PathVariable Long id) {
		if (id == null) {
			id = 0L;
		}
		List<Area> areas = areaDao.listByParentId(id);
		return ApiResult.data(areas);
	}

	@GetMapping("/list")
	@ApiOperation(value = "区域-所有区域")
	public List<Area> list() {
		List<Area> parents = areaDao.listAll();
		return parents;
	}

	/**
	 * 区域树
	 * 
	 * @param pId
	 * @param areasAll
	 * @param array
	 */
	private void setAreasTree(Long pId, List<Area> areasAll, JSONArray array) {
		for (Area per : areasAll) {
			if (per.getParentId().equals(pId)) {
				String string = JSONObject.toJSONString(per);
				JSONObject parent = (JSONObject) JSONObject.parse(string);
				array.add(parent);

				if (areasAll.stream().filter(p -> p.getParentId().equals(per.getAreaId())).findAny() != null) {
					JSONArray child = new JSONArray();
					parent.put("child", child);
					setAreasTree(per.getAreaId(), areasAll, child);
				}
			}
		}
	}

	@LogAnnotation
	@PostMapping
	@ApiOperation(value = "区域-保存区域")
	public void save(@RequestBody Area area) {
		verifyForm(area);// 校验数据
		if(area.getShow() == null){
			area.setShow(0);
		}
		areaDao.save(area);
	}

	@GetMapping("/{id}")
	@ApiOperation(value = "区域-根据区域id获取区域")
	public ApiResult<?> get(@PathVariable Long id) {
		if(id == null){
			return ApiResult.error("要查询的id不能为空");
		}
		Area area = areaDao.getById(id);
		if(area != null){
			Long parentId = area.getParentId();
			List<Long> ids = new ArrayList<Long>();
			while (parentId != null && !parentId.equals(0L)) {
				ids.add(parentId);
				Area areaW = areaDao.getById(parentId);
				if(areaW != null){
					parentId = areaW.getParentId();
				}
			}
			Collections.reverse(ids);
			area.setParentIds(ids);
		}
		return ApiResult.data(area);

	}

	@LogAnnotation
	@PutMapping
	@ApiOperation(value = "区域-修改区域")
	//@PreAuthorize("hasAuthority('sys:menu:add')")
	public void update(@RequestBody Area area) {
		verifyForm(area);// 校验数据
		areaService.update(area);
	}

	@LogAnnotation
	@DeleteMapping("/{id}")
	@ApiOperation(value = "区域-删除区域")
	//@PreAuthorize("hasAuthority('sys:menu:del')")
	public ApiResult<?> delete(@PathVariable Long id) {
		if(id == null){
			return ApiResult.error("要删除的id不能为空");
		}
		areaService.delete(id);
		return ApiResult.ok();
	}

	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(Area area) {
		if (StringUtilsV2.isBlank(area.getAreaName())) {
			throw new IllegalArgumentException("区域名称不能为空");
		}
		// 当前区域类型
		/*
		 * Integer type = area.getAreaType(); if(type == null){ throw new
		 * IllegalArgumentException("区域类型不能为空"); }
		 */
		// 上级区域id
		Long parentId = area.getParentId();
		// 没传父区域id默认为顶级区域
		if (area.getParentId() == null || parentId.equals(0L)) {
			area.setParentId(0L);
			// 默认为顶级
			area.setAreaType(0);
		} else {
			Area parentArea = areaDao.getById(parentId);
			Integer parentType = parentArea.getAreaType();
			if (parentType != null) {
				area.setAreaType(parentType + 1);
			}
		}
	}
	
	@GetMapping("/listAreaSelect")
	@ApiOperation(value = "区域-有效搜索条件")
	public ApiResult<?> listAreaSelect() {
		Map<String, Object> map = new HashMap<>();

		if(map.containsKey("msg")){
			return ApiResult.error(map.get("msg").toString());
		}
		
		return ApiResult.data(map);
	}
}
